<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="标题" prop="title">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入问卷标题"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="问卷状态" clearable>
          <el-option
            v-for="dict in dict.type.survey_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间">
        <el-date-picker
          v-model="dateRange"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:survey:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:survey:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:survey:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:survey:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="surveyList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ID" align="center" prop="surveyId" width="80" />
      <el-table-column label="问卷标题" align="center" prop="title" :show-overflow-tooltip="true" />
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <el-tag :type="statusTypeMap[scope.row.status]">{{ scope.row.status | statusFilter }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="开始时间" align="center" prop="startTime" width="160">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.startTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="结束时间" align="center" prop="endTime" width="160">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.endTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="回答数量" align="center" prop="answerCount" width="80" />
      <el-table-column label="访问数量" align="center" prop="visitCount" width="80" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="160">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:survey:edit']"
            v-if="scope.row.status === '0'"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-s-promotion"
            @click="handleSubmit(scope.row)"
            v-hasPermi="['system:survey:submit']"
            v-if="scope.row.status === '0'"
          >提交审批</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-video-play"
            @click="handlePublish(scope.row)"
            v-hasPermi="['system:survey:publish']"
            v-if="scope.row.status === '0' || scope.row.status === '1'"
          >发布</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-video-pause"
            @click="handleEnd(scope.row)"
            v-hasPermi="['system:survey:end']"
            v-if="scope.row.status === '2'"
          >结束</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handlePreview(scope.row)"
          >预览</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-pie-chart"
            @click="handleStatistics(scope.row)"
            v-if="scope.row.status !== '0' && scope.row.status !== '1'"
          >统计</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改问卷对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="780px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="问卷标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入问卷标题" />
        </el-form-item>
        <el-form-item label="问卷描述" prop="description">
          <el-input v-model="form.description" type="textarea" placeholder="请输入问卷描述" />
        </el-form-item>
        <el-row>
          <el-col :span="12">
            <el-form-item label="开始时间" prop="startTime">
              <el-date-picker clearable
                v-model="form.startTime"
                type="datetime"
                value-format="yyyy-MM-dd HH:mm:ss"
                placeholder="请选择开始时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="结束时间" prop="endTime">
              <el-date-picker clearable
                v-model="form.endTime"
                type="datetime"
                value-format="yyyy-MM-dd HH:mm:ss"
                placeholder="请选择结束时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="是否匿名" prop="anonymous">
              <el-radio-group v-model="form.anonymous">
                <el-radio :label="0">不匿名</el-radio>
                <el-radio :label="1">匿名</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="显示结果" prop="showResult">
              <el-radio-group v-model="form.showResult">
                <el-radio :label="0">不显示</el-radio>
                <el-radio :label="1">显示</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="提交提示" prop="submitTip">
          <el-input v-model="form.submitTip" placeholder="请输入提交成功后的提示语" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 问卷预览对话框 -->
    <el-dialog title="问卷预览" :visible.sync="previewOpen" width="800px" append-to-body>
      <div class="preview-container" v-loading="previewLoading">
        <h2 class="preview-title">{{ previewData.title }}</h2>
        <div class="preview-description">{{ previewData.description }}</div>
        <div class="preview-info">
          <div>开始时间：{{ parseTime(previewData.startTime) }}</div>
          <div>结束时间：{{ parseTime(previewData.endTime) }}</div>
        </div>
        <div class="question-list">
          <div v-if="previewData.questions && previewData.questions.length === 0" class="empty-questions">
            暂无问题，请先添加问题
          </div>
          <div v-else>
            <div class="question-item" v-for="(question, index) in previewData.questions" :key="index">
              <div class="question-title">
                {{ index + 1 }}. {{ question.title }}
                <span class="required" v-if="question.required == 1">*</span>
              </div>
              <div class="question-content" v-if="question.type === 'radio'">
                <el-radio-group disabled>
                  <div v-for="(option, optIndex) in JSON.parse(question.options || '[]')" :key="optIndex">
                    <el-radio :label="optIndex">{{ option.label }}</el-radio>
                  </div>
                </el-radio-group>
              </div>
              <div class="question-content" v-else-if="question.type === 'checkbox'">
                <el-checkbox-group disabled>
                  <div v-for="(option, optIndex) in JSON.parse(question.options || '[]')" :key="optIndex">
                    <el-checkbox :label="optIndex">{{ option.label }}</el-checkbox>
                  </div>
                </el-checkbox-group>
              </div>
              <div class="question-content" v-else-if="question.type === 'text'">
                <el-input type="textarea" disabled placeholder="请输入" />
              </div>
              <div class="question-content" v-else-if="question.type === 'rate'">
                <el-rate disabled />
              </div>
            </div>
          </div>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="previewOpen = false">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listSurveyQuestionnaire, getSurveyQuestionnaire, delSurveyQuestionnaire, addSurveyQuestionnaire, updateSurveyQuestionnaire, publishSurveyQuestionnaire, endSurveyQuestionnaire, submitSurveyApproval } from "@/api/system/survey";

export default {
  name: "Survey",
  dicts: ['survey_status'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 问卷表格数据
      surveyList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 预览问卷弹窗
      previewOpen: false,
      // 预览问卷数据
      previewData: {},
      // 预览加载状态
      previewLoading: false,
      // 状态类型映射
      statusTypeMap: {
        '0': '',      // 草稿
        '1': 'info',  // 待审核
        '2': 'success', // 已发布
        '3': 'warning', // 已结束
        '4': 'danger'  // 已归档
      },
      // 日期范围
      dateRange: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        title: undefined,
        status: undefined
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        title: [
          { required: true, message: "问卷标题不能为空", trigger: "blur" }
        ],
        startTime: [
          { required: true, message: "开始时间不能为空", trigger: "blur" }
        ],
        endTime: [
          { required: true, message: "结束时间不能为空", trigger: "blur" }
        ]
      }
    };
  },
  filters: {
    statusFilter(status) {
      const statusMap = {
        '0': '草稿',
        '1': '待审核',
        '2': '已发布',
        '3': '已结束',
        '4': '已归档'
      }
      return statusMap[status]
    }
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询问卷列表 */
    getList() {
      this.loading = true;
      listSurveyQuestionnaire(this.queryParams).then(response => {
        this.surveyList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        surveyId: undefined,
        title: undefined,
        description: undefined,
        startTime: undefined,
        endTime: undefined,
        status: "0",
        anonymous: 0,
        showResult: 0,
        submitTip: "感谢您的参与！",
        remark: undefined
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.surveyId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.$router.push({ path: '/system/survey/design' });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      const surveyId = row.surveyId || this.ids[0]
      this.$router.push({ 
        path: '/system/survey/design',
        query: { id: surveyId }
      });
    },
    /** 提交按钮操作 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.surveyId !== undefined) {
            updateSurveyQuestionnaire(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addSurveyQuestionnaire(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const surveyIds = row.surveyId || this.ids;
      this.$modal.confirm('是否确认删除问卷编号为"' + surveyIds + '"的数据项？').then(function() {
        return delSurveyQuestionnaire(surveyIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/survey/export', {
        ...this.queryParams
      }, `survey_${new Date().getTime()}.xlsx`)
    },
    /** 提交审批操作 */
    handleSubmit(row) {
      const surveyId = row.surveyId;
      this.$modal.confirm('确认提交该问卷进行审批吗？').then(function() {
        return submitSurveyApproval(surveyId);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("提交成功");
      }).catch(() => {});
    },
    /** 发布问卷操作 */
    handlePublish(row) {
      const surveyId = row.surveyId;
      this.$modal.confirm('确认发布该问卷吗？').then(function() {
        return publishSurveyQuestionnaire(surveyId);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("发布成功");
      }).catch(() => {});
    },
    /** 结束问卷操作 */
    handleEnd(row) {
      const surveyId = row.surveyId;
      this.$modal.confirm('确认结束该问卷吗？结束后将不能再答卷。').then(function() {
        return endSurveyQuestionnaire(surveyId);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("操作成功");
      }).catch(() => {});
    },
    /** 预览问卷 */
    handlePreview(row) {
      this.previewOpen = true;
      this.previewLoading = true;
      getSurveyQuestionnaire(row.surveyId).then(response => {
        this.previewData = response.data;
        this.previewLoading = false;
      });
    },
    /** 统计分析 */
    handleStatistics(row) {
      this.$router.push({ 
        path: '/system/survey/statistics',
        query: { surveyId: row.surveyId }
      })
    }
  }
};
</script>

<style scoped>
.preview-container {
  padding: 20px;
}
.preview-title {
  text-align: center;
  margin-bottom: 15px;
}
.preview-description {
  margin-bottom: 20px;
  color: #666;
  text-align: center;
}
.preview-info {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
  color: #999;
  font-size: 14px;
}
.question-list {
  margin-top: 30px;
}
.question-item {
  margin-bottom: 25px;
  padding-bottom: 15px;
  border-bottom: 1px solid #eee;
}
.question-title {
  font-weight: bold;
  margin-bottom: 10px;
}
.question-content {
  margin-left: 20px;
}
.required {
  color: #f56c6c;
  margin-left: 5px;
}
.empty-questions {
  text-align: center;
  color: #999;
  padding: 30px;
}
</style> 